﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace FrameWorkSong
{
    public class ImgMgr : Singleton<ImgMgr>
    {
        public override void OnBeforeDestroy(){}

         public byte[] BuildTexture()
        {
            Camera camera = Camera.main;
            //尺寸
            Rect rect = new Rect(0, 0, 1920, 1080);
            // 创建一个RenderTexture对象  、设置渲染图片的大小和深度
            RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 2);
            // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
            camera.targetTexture = rt;
            //渲染相机
            camera.Render();
            // 激活rt, 从中中读取像素
            RenderTexture.active = rt;
            Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
            Sprite _sprite = Sprite.Create(screenShot, new Rect(0, 0, screenShot.width, screenShot.height), new Vector2(0.5f, 0.5f));
            // texture2.GetComponent<Image>().sprite = _sprite;
            // 从RenderTexture.active中读取像素  
            screenShot.ReadPixels(rect, 0, 0, false);
            //改变像素设置之后调用的方法（）
            screenShot.Apply();
            //刷新
            // 重置相关参数，以使用camera继续在屏幕上显示  
            camera.targetTexture = null;
            //ps: camera2.targetTexture = null;  
            RenderTexture.active = null;
            GameObject.DestroyImmediate(rt);
            // 最后将这些纹理数据，成一个png图片文件  
            byte[] bytes = screenShot.EncodeToPNG();
            return bytes;
            //转Base64方法
            //string bytesToString = Convert.ToBase64String(bytes);
            //Debug.Log(bytesToString);

            //保存test
            //string filename = Application.dataPath + "/filename.jpg";
            //Debug.Log(string.Format("截屏了一张照片: {0}", filename));
            //if (File.Exists(filename)) File.Delete(filename);
            //System.IO.File.WriteAllBytes(filename, bytes);

        }
    }
}
